package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void save(Notice notice) {
        noticeMapper.insert(notice);
    }

    @Override
    public void delete(Long id) {
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(Employee employee,QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),"en.read_status,n.level");
        List<Notice> notices = noticeMapper.selectPaging(employee,qo);
        return new PageInfo<>(notices);
    }

    @Override
    public void saveRelation(Long empId, Long notId,boolean readStatus) {
        noticeMapper.saveRelation(empId,notId,readStatus);
    }

    @Override
    public void updateRelation(Long empId, Long notId) {
        noticeMapper.updateRelation(empId,notId);
    }

    @Override
    public boolean selectRead(Long empId, Long notId) {
        Boolean read = noticeMapper.selectRead(empId, notId);
        if(read == null){
            return false;
        }
        return read;
    }

    @Override
    public void updateIssueById(Long id,Boolean issue) {
        //如果issue是true,原本是未发布,点击了要发布
        //获取到所有员工的id
        //给所有员工和公告的关系表进行新增或者删除
        List<Long> ids = employeeMapper.selectIds();

        noticeMapper.deleteRelationByNotId(id);

        if(issue){
            //先清空关系表再添加
            noticeMapper.saveRelationByIds(ids,id);
        }else{
            //删除关系表,保留管理员的
            noticeMapper.saveRelation(UserContext.getCurrentUser().getId(),id,false);
        }

        //设置公告是否发布的状态
        noticeMapper.updateIssueById(id,issue);
    }
}
